import { createSlice } from "@reduxjs/toolkit";
import { setTokenToLocal, getToken,removeToken } from "@/utils/token";
import { logout as logoutApi } from "@/api/auth";

const userAuthStore = createSlice({
  name: "user",
  initialState: {
    token: getToken() || "",
  },
  reducers: {
    setToken(state, action) {
      state.token = action.payload;
      setTokenToLocal(action.payload);
    },
    logout() {
      logoutApi().then((res) => {
        if(res.code === 200) {
          removeToken();
          window.location.href = "/login";
        }
      })
    },



  },
});

const { setToken, logout } = userAuthStore.actions;
export { setToken,logout };
export default userAuthStore.reducer;
